<template>
  <el-card class="content-card">
    <template #header>
      <div class="card-header">
        <h3>合同金额统计</h3>
      </div>
    </template>

    <!-- 日期区间选择器 -->
    <el-button-group class="period-selector" style="margin-bottom: 16px">
      <el-button :type="selectedPeriod === 'today' ? 'primary' : ''" @click="changePeriod('today')">
        本日
      </el-button>
      <el-button :type="selectedPeriod === 'week' ? 'primary' : ''" @click="changePeriod('week')">
        本周
      </el-button>
      <el-button :type="selectedPeriod === 'month' ? 'primary' : ''" @click="changePeriod('month')">
        本月
      </el-button>
      <el-button
        :type="selectedPeriod === 'quarter' ? 'primary' : ''"
        @click="changePeriod('quarter')"
      >
        本季度
      </el-button>
    </el-button-group>

    <!-- 图表展示 -->
    <div ref="contractAmountChart" class="chart-container"></div>

    <!-- 数据表格 -->
    <el-table
      v-if="getSelectedFinanceData() && getSelectedFinanceData().length > 0"
      :data="getSelectedFinanceData()"
      style="margin-top: 16px"
      size="small"
      border
    >
      <el-table-column prop="contract_type" label="合同类型" width="180"></el-table-column>
      <el-table-column
        prop="contract_count"
        label="合同数"
        width="100"
        align="right"
      ></el-table-column>
      <el-table-column prop="contract_amount_format" label="合同金额" width="160" align="right">
        <template #default="scope">
          <span style="font-weight: 500; color: #4facfe">
            ¥{{ scope.row.contract_amount_format }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="payment_amount_format" label="到账金额" width="160" align="right">
        <template #default="scope">
          <span style="font-weight: 500; color: #fa709a">
            ¥{{ scope.row.payment_amount_format }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="trend" label="趋势" width="120" align="center">
        <template #default="scope">
          <div v-if="scope.row.trend" class="trend-item">
            <el-icon :size="14" :class="getTrendClass(scope.row.trend.type)">
              <component
                :is="
                  scope.row.trend.type === 'up'
                    ? ElementPlusIconsVue.ArrowUp
                    : scope.row.trend.type === 'down'
                      ? ElementPlusIconsVue.ArrowDown
                      : ElementPlusIconsVue.Minus
                "
              />
            </el-icon>
            <span :class="getTrendClass(scope.row.trend.type)">{{ scope.row.trend.value }}%</span>
          </div>
          <span v-else class="text-gray-400">--</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <div v-else class="no-data">暂无数据</div>
  </el-card>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  import * as ElementPlusIconsVue from '@element-plus/icons-vue'

  interface ContractAmountStat {
    name: string
    contract_type: string
    contract_count: number
    contract_amount: number
    contract_amount_format: string
    payment_amount: number
    payment_amount_format: string
    trend?: {
      type: 'up' | 'down' | 'stable'
      value: number
    }
  }

  interface FinanceByPeriod {
    today: ContractAmountStat[]
    week: ContractAmountStat[]
    month: ContractAmountStat[]
    quarter: ContractAmountStat[]
  }

  interface Props {
    financeByPeriod: FinanceByPeriod
  }

  const props = defineProps<Props>()

  // 图表实例引用
  const contractAmountChart = ref<HTMLElement>()
  let contractAmountChartInstance: echarts.ECharts | null = null

  // 当前选择的日期区间
  const selectedPeriod = ref<'today' | 'week' | 'month' | 'quarter'>('today')

  // 获取当前选中的财务数据
  const getSelectedFinanceData = () => {
    const dataMap = {
      today: props.financeByPeriod?.today || [],
      week: props.financeByPeriod?.week || [],
      month: props.financeByPeriod?.month || [],
      quarter: props.financeByPeriod?.quarter || [],
    }
    return dataMap[selectedPeriod.value]
  }

  // 获取趋势样式类
  const getTrendClass = (trendType: string) => {
    return trendType === 'up' ? 'trend-up' : trendType === 'down' ? 'trend-down' : 'trend-stable'
  }

  // 初始化图表
  const initChart = () => {
    if (contractAmountChart.value) {
      contractAmountChartInstance = echarts.init(contractAmountChart.value)
      updateChart()
    }
  }

  // 更新图表数据
  const updateChart = () => {
    if (!contractAmountChartInstance) return

    const financeData = getSelectedFinanceData()

    if (financeData && financeData.length > 0) {
      const contractTypeData = financeData.map(item => item.contract_type)
      const contractAmountData = financeData.map(item => item.contract_amount)
      const paymentAmountData = financeData.map(item => item.payment_amount)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          formatter: (params: any) => {
            const dataIndex = params[0].dataIndex
            const item = financeData[dataIndex]
            return (
              `${item.contract_type}<br/>合同数: ${item.contract_count} 笔<br/>` +
              `合同金额: ${item.contract_amount_format}<br/>` +
              `到账金额: ${item.payment_amount_format}`
            )
          },
        },
        legend: {
          data: ['合同金额', '到账金额'],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: contractTypeData,
          axisLabel: {
            rotate: 30,
          },
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}',
          },
        },
        series: [
          {
            name: '合同金额',
            type: 'bar',
            data: contractAmountData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#4facfe' },
                { offset: 1, color: '#00f2fe' },
              ]),
            },
          },
          {
            name: '到账金额',
            type: 'bar',
            data: paymentAmountData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#fa709a' },
                { offset: 1, color: '#fee140' },
              ]),
            },
          },
        ],
      } as any
      contractAmountChartInstance.setOption(option, true)
    }
  }

  // 切换日期区间
  const changePeriod = (period: 'today' | 'week' | 'month' | 'quarter') => {
    selectedPeriod.value = period
    updateChart()
  }

  // 图表响应式调整
  const handleResize = () => {
    contractAmountChartInstance?.resize()
  }

  // 监听数据变化
  watch(
    () => props.financeByPeriod,
    () => {
      updateChart()
    },
    { deep: true }
  )

  // 组件挂载时
  onMounted(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })

  // 组件卸载时
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    contractAmountChartInstance?.dispose()
  })
</script>

<style scoped lang="scss">
  .content-card {
    margin-bottom: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }

  .chart-container {
    width: 100%;
    height: 300px;
  }

  .period-selector {
    display: flex;
    justify-content: flex-end;
  }

  .trend-item {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
  }

  .text-gray-400 {
    color: #909399;
  }

  .trend-up {
    color: #f56c6c;
  }

  .trend-down {
    color: #67c23a;
  }

  .trend-stable {
    color: #909399;
  }

  .no-data {
    text-align: center;
    color: #909399;
    padding: 20px 0;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .chart-container {
      height: 250px !important;
    }
  }
</style>
